package com.nuliji.help;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.nuliji.constants.SessionKey;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.Properties;

/**
 * Created by GaoJie on 2017/11/3.
 */
@Service
public class CaptchaHelp {
    private static DefaultKaptcha kaptcha;

    static {
        kaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.image.width", "100");
        properties.setProperty("kaptcha.image.height", "50");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        kaptcha.setConfig(new Config(properties));
    }

    public boolean verify(String captcha, HttpSession session){
        String code = (String) session.getAttribute(SessionKey.CAPTCHA_KEY);
        session.removeAttribute(SessionKey.CAPTCHA_KEY);
        return StringUtils.equalsIgnoreCase(captcha, code);
    }

    public BufferedImage createImage(HttpSession session) {
        return kaptcha.createImage(create(session));
    }

    private String create(HttpSession session){
        String code = kaptcha.createText();
        session.setAttribute(SessionKey.CAPTCHA_KEY, code);
        return code;
    }
}
